/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.i18n.utils;

import io.iec.edp.caf.i18n.framework.api.language.EcpLanguage;
import io.iec.edp.caf.i18n.framework.api.language.ILanguageService;
import io.iec.edp.caf.security.core.spring.language.Language;
import io.iec.edp.caf.security.core.spring.language.LanguageTranslator;
import io.iec.edp.caf.tenancy.api.context.MultiTenantContextInfo;
import io.iec.edp.caf.tenancy.core.context.MultiTenantContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 语言翻译器，将登陆的语言映射到iGIX的语言
 * @author wangyandong
 * @date 2020/07/23 09:34
 * @email wangyandong@inspur.com
 */
public class CAFLanguageTranslator implements LanguageTranslator {
    private final String tenantField = "Tenant";
    private final ILanguageService languageService;

    public CAFLanguageTranslator(ILanguageService languageService){
        this.languageService = languageService;
    }

    @Override
    public String translate(Language lang){
        //优先使用Url参数中的
        if(lang.getUrlLanguage()!=null && !"".equals(lang.getUrlLanguage())){
            return lang.getUrlLanguage();
        }

        //根据上下文获取租户等信息
        int tenantId = -1;
        String appCode = "pg01";
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String tenant = request.getParameter(tenantField);
            if(tenant!=null && !"".equals(tenant)) {
                tenantId = Integer.parseInt(tenant);
            }
        }
        //系统默认语言
        String language = null;
        //获取到语言列表:
        List<EcpLanguage> list = this.getLanguages(tenantId, appCode,"Sys");
        List<String> languages = new ArrayList<>();
        list.forEach((l)->{ languages.add(l.getId());});
        //再次使用UserDetail中的
        if(lang.getUserDetailsLanguage()!=null && !"".equals(lang.getUserDetailsLanguage())){
            language = this.findBestMatch(lang.getUserDetailsLanguage(),languages);
        }

        //最后考虑Header中
        if(language==null && lang.getHeaderLanguage()!=null && lang.getHeaderLanguage().size()>0){
            language = lang.getHeaderLanguage().stream().filter((l)->{
                return null != this.findBestMatch(l,languages);
            }).findFirst().orElse(null);
            for(int i=0;i<lang.getHeaderLanguage().size();i++){
                language = this.findBestMatch(lang.getHeaderLanguage().get(i),languages);
                if(language!=null)
                    break;
            }
        }

        return language!=null?language:"zh-CHS";
    }

    /**
     * 获取当前系统支持的语言列表
     * @param tenantId
     * @param appCode
     * @param su
     * @return
     */
    private List<EcpLanguage> getLanguages(int tenantId, String appCode, String su){
        try{
            MultiTenantContextInfo contextInfo = new MultiTenantContextInfo();
            contextInfo.setTenantId(tenantId);
            contextInfo.setAppCode(appCode);
            contextInfo.setServiceUnit(su);
            MultiTenantContextHolder.set(contextInfo);
            //获取语言
            return this.languageService.getEnabledLanguages();
        }finally {
            MultiTenantContextHolder.set(null);
        }
    }

    /**
     * 查找最佳匹配的语言
     * @param language
     * @param languages
     * @return
     */
    private String findBestMatch(String language, List<String> languages){
        if(language==null || "".equals(language) || languages==null || languages.size()<=0)
            return null;
        //中文需要强识别进行特殊处理
        if("zh-CN".equals(language) || "zh-Hans".equals(language)) {
            language = "zh-CHS";
        } else if("zh-TW".equals(language) || "zh-HK".equals(language))
            language = "zh-CHT";

        //尝试完全匹配
        if(languages.contains(language))
            return language;

        //按照第一节进行完整匹配
        language = language.split("-")[0];
        if(languages.contains(language))
            return language;

        //按照第一节进行模糊匹配（仅对应第一节）
        language = language.split("-")[0];
        for(int i=0;i<languages.size();i++){
            if(languages.get(i).startsWith(language))
                return languages.get(i);
        }

        return null;
    }
}

